﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Xiaowei.Services.TencentVideoArgs;
using Log = Logger.Debug;


namespace Xiaowei.Services
{
    namespace TencentVideoArgs
    {
        public interface ITencentVideoAiagentFeedback
        {
            void OnFeedback(AiAgentFeadback feadback);
            void OnMessage(AiAgentMessage message);
        }
        public struct AiAgentMessage
        {
            public string messageId;
            public string messageIdOfReply;
            public VoiceMessageCode code;
            public string message;
        }
        public struct AiAgentFeadback
        {
            public string voiceId;
            public int code;
            public string text;
        }
        public enum VoiceFeedbackCode
        {
            SUCEESS = 1000,//成功处理请求
            RECEIVED = 1003,//视频端已收到请求，msg为原发送文本

            //腾讯视频由SDK自动拉起，连接方面的消息不需要处理
            //public const int CONNECTED = 1001;//连接成功
            //public const int DISCONNECTED = 1002;//连接断开

            FAILURE = -1000,//失败
            AUTH_ERROR = -1001,//认证错误
            UNHANDLED = -1002,//未知错误
        }

        public enum VoiceMessageCode
        {
            RECEIVED = 1003,//视频端已收到消息，本code为SDK使用，禁止修改

            //以下可自定义,示例
            NORMAL = 1,//普通消息
            GET_STATE = 2,//用于获取播放状态
        }

        public enum SendResultCode
        {
            ERRCODE_OPEN_TENENT_VIDEO = -4,//拉起腾讯视频失败
        }
        public delegate void FeedbackCallback(string voiceId, int code, IntPtr data_u8, int size);
        public delegate void MessageCallback(string messageId, string messageIdOfReply, int code, IntPtr data_u8, int size);
    }

    public interface ITencentVideoService
    {
        void Init(string appId, string appKey, string appSecret, ITencentVideoAiagentFeedback iaigent, bool isEnableLog);
        int SendVoiceText(string text);
        int SendMessage(ref string messageId, VoiceMessageCode code, string message, bool isOpenQQLive);
        int ReplyMessage(ref string messageId, string messageIdOfReply, int code, string message, bool isOpenQQLive);
        bool VideoIsLive();
    }
    internal class TencentVideoService: ITencentVideoService
    {
        private ITencentVideoAiagentFeedback mIAiagent;
        [DllImport("aiagent-device.dll", CharSet = CharSet.Ansi)]
        private static extern void AiAgentInit(string appId, string appKey, string appSecret, FeedbackCallback feedbackCallback, MessageCallback messageCallback, bool isEnableLog);

        [DllImport("aiagent-device.dll", CharSet = CharSet.Ansi)]
        private static extern int AiAgentSendVoiceText(IntPtr data_u8, int length);

        [DllImport("aiagent-device.dll", CharSet = CharSet.Ansi)]
        private static extern int AiAgentSendMessage(IntPtr messageId, string messageFeadbackId, int code, IntPtr message, int size, bool isOpenQQLive);

        private void FeedbackCallbackImp(string voiceId, int code, IntPtr data_u8, int size)
        {
            byte[] str_u8 = new byte[size];
            Marshal.Copy(data_u8, str_u8, 0, size);
            string text = System.Text.Encoding.GetEncoding("utf-8").GetString(str_u8);
            AiAgentFeadback aiAgentFeadback = new AiAgentFeadback();
            aiAgentFeadback.code = code;
            aiAgentFeadback.voiceId = voiceId;
            aiAgentFeadback.text = text;
            mIAiagent.OnFeedback(aiAgentFeadback);
        }

        private void MessageCallbackImp(string messageId, string messageIdOfReply, int code, IntPtr data_u8, int size)
        {
            byte[] str_u8 = new byte[size];
            Marshal.Copy(data_u8, str_u8, 0, size);
            string msg = System.Text.Encoding.GetEncoding("utf-8").GetString(str_u8);

            AiAgentMessage aiAgentMessage = new AiAgentMessage();
            aiAgentMessage.code = (VoiceMessageCode)code;
            aiAgentMessage.messageId = messageId;
            aiAgentMessage.messageIdOfReply = messageIdOfReply;
            aiAgentMessage.message = msg;

            mIAiagent.OnMessage(aiAgentMessage);
        }

        private static IntPtr BytesToIntptr(byte[] bytes)
        {
            int size = bytes.Length;
            IntPtr buffer = Marshal.AllocHGlobal(size);
            Marshal.Copy(bytes, 0, buffer, size);
            //GC.KeepAlive(fd);
            return buffer;
        }
        FeedbackCallback feedbackCallback;
        MessageCallback messageCallback;
        public void Init(string appId, string appKey, string appSecret, ITencentVideoAiagentFeedback iaigent, bool isEnableLog)
        {
            feedbackCallback=new FeedbackCallback(FeedbackCallbackImp);
            messageCallback = new MessageCallback(MessageCallbackImp);
            AiAgentInit(appId, appKey, appSecret, feedbackCallback, messageCallback, isEnableLog);//启动与腾讯视频端的通信
            mIAiagent = iaigent;
            GC.KeepAlive(feedbackCallback);
            GC.KeepAlive(messageCallback);
        }

        public int SendVoiceText(string text)
        {
            byte[] t = System.Text.Encoding.GetEncoding("utf-8").GetBytes(text);
            int ret = AiAgentSendVoiceText(BytesToIntptr(t), t.Length);//发送ASR文本
            return ret;
        }

        public int SendMessage(ref string messageId, VoiceMessageCode code, string message, bool isOpenQQLive)
        {
            byte[] msg_u8 = System.Text.Encoding.GetEncoding("utf-8").GetBytes(message);
            IntPtr msg_u8_ptr = BytesToIntptr(msg_u8);
            IntPtr buffer = Marshal.AllocHGlobal(128);
            int ret = AiAgentSendMessage(buffer, "", (int)code, msg_u8_ptr, msg_u8.Length, isOpenQQLive);//发送ASR文本
            messageId = Marshal.PtrToStringAnsi(buffer);
            return ret;
        }
        public int ReplyMessage(ref string messageId, string messageIdOfReply, int code, string message, bool isOpenQQLive)
        {
            byte[] msg_u8 = System.Text.Encoding.GetEncoding("utf-8").GetBytes(message);
            IntPtr msg_u8_ptr = BytesToIntptr(msg_u8);
            IntPtr buffer = Marshal.AllocHGlobal(128);
            int ret = AiAgentSendMessage(buffer, messageIdOfReply, code, msg_u8_ptr, msg_u8.Length, isOpenQQLive);//发送ASR文本
            messageId = Marshal.PtrToStringAnsi(buffer);
            return ret;
        }

        public bool VideoIsLive()
        {
            bool flag = false;

            string processName = "QQLive";
            Process[] process = Process.GetProcessesByName(processName);
            if (process.Length > 0)
            {
                flag = true;
            }
            string lg = string.Format("the VideoIsLive flag is {0} ", flag.ToString());
            Log.WriteLine(lg);
            return flag;
        }
    }




}
